/**
 * 
 */
package org.vidyakiran.app.server.dao.impl;

import java.util.List;

import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;

import org.springframework.stereotype.Repository;
import org.vidyakiran.app.server.dao.UserDetailDao;
import org.vidyakiran.app.server.dao.util.DatabaseUtils;
import org.vidyakiran.app.server.domain.entity.User;
import org.vidyakiran.app.server.domain.entity.VolunteeringActivity;

import com.google.appengine.api.datastore.Key;


/** Methods for saving and fetching the User entity.
 * 
 * @author Harpreet
 */
@Repository
public class UserDetailDaoJpaImpl implements UserDetailDao {

	EntityManager em;
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public User findUserDetailsById(Key userId) {
		em = DatabaseUtils.startTransaction(em);

		User user = null;
		try {
			user = em.find(User.class, userId);
			//Get the child objects, is weird but thats the way child objects can be fetched/initialized on GAE
			user.getContacts();
			user.getAddress();
			user.getCategories();
			
			em.getTransaction().commit();
		} finally {
			DatabaseUtils.cleanupTransaction(em);
		}
		return user;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public User saveOrUpdateUserDetails(User user) {
		em = DatabaseUtils.startTransaction(em);
		
		//Checks for Activities, and persists the keys. This is a workaround for ManyToMany limitation on GAE
		List<VolunteeringActivity> activities = user.getActivities();
		user.getActivityKeys().clear();
		for (VolunteeringActivity activity : activities) {
			user.getActivityKeys().add(activity.getId());
		}
		
		try {
			em.persist(user);
			em.getTransaction().commit();
		} catch (EntityExistsException ex) {
			user = em.merge(user);
			em.getTransaction().commit();
		} finally {
			DatabaseUtils.cleanupTransaction(em);
		}
		//Push back the transient activities collection
		user.setActivities(activities);
		return user;
	}

}
